<?php

namespace app\common\business;


use app\common\lib\Show;
use app\common\model\MallGroupsGoods as ModelObj;
use app\common\model\MallGroupsTeam;
use app\common\model\MallGroupsOrder;
use app\common\model\MallManager;
use app\common\model\MallMember;
use think\Exception;
use think\Model;

class Group extends Base
{

    /**
     * @var ModelObj
     */
    protected ModelObj $modelObj;

    /**
     *
     */
    public function __construct()
    {
        $this->modelObj = new ModelObj();
    }

    /**
     * 拼团商品
     * @param array $where
     * @param string $field
     * @return array
     * @throws Exception
     */
    public function  getShowIndexGroupsGoods(array $where,string $field='*',$limit,$lat,$lng){
        try{
            $list =$this->modelObj->getModelByListTolimitArray($where,$field,$limit,'displaysort desc,create_time desc');
        }catch (\Exception $e){
            throw new Exception("查询失败");
        }
        if($list){
            foreach($list as $k=>$v){
                if($v['mendian']){
                    $mendian =json_decode($v['mendian'],true);
                    if($lat !=0 && $lng!=0 && $mendian[0]['store_lng']!=0 && $mendian[0]['store_lat'] !=0){
                        $list[$k]['juli'] =Show::getDistances($lng,$lat,$mendian[0]['store_lng'],$mendian[0]['store_lat'],2);
                    }else{
                        $list[$k]['juli'] ='...';
                    }
                }else{
                    $list[$k]['juli'] ='...';
                }
            }
            $last_names = array_column($list,'juli');
            array_multisort($last_names,SORT_ASC,$list);
        }
        return $list;
    }

    /**
     * 执行过期订单更新
     * @param $openid
     * @return bool
     * @throws Exception
     */
    public function getGroupsOrderByAll($openid){
        $shoptime =(new Member())->getSystenConfig('shoptime');
        $endtime =time()-$shoptime*60;
        try{
            $list=(new MallGroupsOrder())->field('id,ordersn')->where("openid='$openid' and status=0 and create_time<'".$endtime."'")->select()->toArray();
        }catch(\Exception $e){
            throw new Exception("查询失败");
        }

        if($list){
            foreach ($list as $k=>$v){
                (new MallGroupsOrder())->where("id ='".$v['id']."'")->save(array('status'=>-1,'canceltime'=>time()));
            }
        }
        return true;
    }

    public function getGroupsOrderByAllList(){
        $shoptime =(new Member())->getSystenConfig('shoptime');
        $endtime =time()-$shoptime*60;
        try{
            $list=(new MallGroupsOrder())->field('id,ordersn')->where("status=0 and create_time<'".$endtime."'")->select()->toArray();
        }catch(\Exception $e){
            throw new Exception("查询失败");
        }

        if($list){
            foreach ($list as $k=>$v){
                (new MallGroupsOrder())->where("id ='".$v['id']."'")->save(array('status'=>-1,'canceltime'=>time()));
            }
        }
        return true;
    }

    /**
     * 下单
     * @param $data
     * @return mixed
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function saveData($data){

        try {
            $orderinfo = (new MallGroupsOrder())->save($data);
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
        $order =(new MallGroupsOrder())->getModelByInfo([['ordersn','=',$data['ordersn']]],'*');
        return $order['id'];
    }


    /**
     * 分页获取拼团商品
     * @param $page
     * @return array
     * @throws Exception
     */
    public function getShowGroupsGoods($page,$where,$lng,$lat){
        try{
           $list= $this->modelObj->field('id,logo,title,groupnum,groupsprice,price,clicknum,endtime,mendian')
                ->where($where)
                ->page($page,10)
                ->select()
                ->toArray();
        }catch (\Exception $e){
            throw new Exception("查询失败");
        }
        if($list){
            foreach ($list as $k=>$v){
                if($v['mendian']){
                    $mendian =json_decode($v['mendian'],true);
                }
                // 拼团距离待解决
                if($lat !=0 && $lng!=0 && $mendian[0]['store_lng']!=0 && $mendian[0]['store_lat'] !=0){
                    $list[$k]['juli'] =Show::getDistances($lng,$lat,$mendian[0]['store_lng'],$mendian[0]['store_lat'],2);
                }else{
                    $list[$k]['juli'] ='...';
                }
                if($v['endtime']<time()){
                    $list[$k]['statuname'] ='已结束';
                }else{
                    $list[$k]['statuname'] ='去开团';
                }
            }
        }
        return $list;
    }

    /**
     * @param array $where
     * @param string $field
     * @return array|\think\Model|null
     * @throws Exception
     */
    public function getGoodsInfo(array $where,string $field='*'){

        try{
            $info =$this->modelObj->getModelByInfo($where,$field);
        }catch (\Exception $e){
            throw new Exception("查询失败");
        }
        if($info){
            if($info['images']){
                $images =explode('|',$info['images']);
                $info['images'] =$images;
            }
            // 开团情况
            $single=[];
            $teamlist =(new MallGroupsTeam())->field('id as team_id,openid')
                ->where("parent_id =0 and status=0 and goods_id='".$info['id']."'")->select()->toArray();
            foreach ($teamlist as $k=>$v){


                $child=(new MallGroupsTeam())->alias('t')
                    ->field('t.id,m.nickName,m.avatarUrl')
                    ->join('mall_member m','m.openid=t.openid')
                    ->where("t.openid='".$v['openid']."' and t.status=0 and goods_id='".$info['id']."'")
                    ->select()
                    ->toArray();
                $num =$info['groupnum']-count($child);
                $teamlist[$k]['child']=$child;
                for($i=count($child);$i<=$num;$i++){
                    $teamlist[$k]['child'][$i]=[];
                }
            }
            $info['team'] =$teamlist;
        }

        return $info;
    }

    /**
     * 查询指定团购订单
     * @param $order_id
     * @return array|Model|null
     * @throws Exception
     */
    public function getOrderById($order_id){
        try{
           $info= (new MallGroupsOrder())->getModelByInfo([['id','=',$order_id]],'*');
        }catch (\Exception $e){
            throw new Exception("团购订单查询失败");
        }
        return $info;
    }


    /**
     * 根据订单号查询商家信息
     * @param $order_id
     * @return mixed
     * @throws Exception
     */
    public function getOrderAndManager($order_id){

        try{
            $minfo= (new MallGroupsOrder())->alias('o')
                ->field('m.id as mid,m.title,m.weixinno,m.openid,o.manager_id,o.status,o.isverify,o.id,o.first_price,o.parent_openid,o.openid,o.payprice')
                ->join('mall_groups_goods gg','gg.id=o.goods_id')
                ->join('mall_manager m','m.id=gg.manager_id')
                ->where("o.id='$order_id'")
                ->find();
        }catch (\Exception $e){
            throw new Exception("团购订单查询失败");
        }

        return $minfo;

    }



    public function getOrdersByIdGoods($order_id,$openid){
        try{
            $info= (new MallGroupsOrder())->getModelByInfo([['id','=',$order_id],['openid','=',$openid]],'*');
        }catch (\Exception $e){
            throw new Exception("团购订单查询失败");
        }

        if($info){
            $goods =[];
            $manager=(new MallManager())->alias('m')->field('m.id,m.title')->join('mall_groups_goods g','g.manager_id=m.id')
                ->where("g.id='".$info['goods_id']."'")->find();

            $goods[0]['title']=$manager['title'];
            $goods[0]['id']=$manager['id'];
            $goods[0]['goods'][0]['id'] =$info['goods_id'];
            $goods[0]['goods'][0]['goods_name'] =$info['goods_name'];
            $goods[0]['goods'][0]['logo'] =$info['goodslogo'];
            $goods[0]['goods'][0]['total'] =$info['groupnum'];
            $goods[0]['goods'][0]['price'] =$info['price'];
            switch ($info['status']){
                case 0:
                    $info['statusname'] ='待支付';
                    break;
                case 1:
                    $info['statusname'] ='待核销';
                    break;
                case 2:
                    $info['statusname'] ='已完成';
                    break;
                case 3:
                    $info['statusname'] ='售后中';
                    break;
                case 4:
                    $info['statusname'] ='已退款';
                    break;
                default:
                    $info['statusname'] ='已取消';
                    break;
            }
            $info['goods']=$goods;
        }
        return $info;
    }




    /**
     * 根据订单号查询团购订单
     * @param $openid
     * @param $ordersn
     * @param string $field
     * @return array|Model|null
     * @throws Exception
     */
    public function getOrderByOrdersn($openid,$ordersn,$field='*'){

        try{
            $info= (new MallGroupsOrder())->getModelByInfo([['ordersn','=',$ordersn],['openid','=',$openid]],$field);
        }catch (\Exception $e){
            throw new Exception("团购订单查询失败");
        }

        if($info){
            $shoptime =(new Member())->getSystenConfig('shoptime');

            //$info['end_time'] =$info['create_time']+$shoptime*60;

            switch ($info['status']){
                case 0:
                    $info['statusname'] ='待付款';
                    break;
                case 1:
                    $info['statusname'] ='待核销';
                    break;
                case 2:
                    $info['statusname'] ='已完成';
                    break;
                case 3:
                    $info['statusname'] ='售后';
                    break;
                default:
                    $info['statusname'] ='已取消';
                    break;
            }
        }
        return $info;
    }

    /**
     * @param $opneid
     * @param $page
     * @return array
     * @throws Exception
     */
    public function getGroupsByOrder($openid,$page,$type){
        $where=[];
        if($type!='-1'){
            if($type ==1){
                $where[] = [
                    ['deleted','=',0],['isverify','=',0],['openid','=',$openid],['status','=',1]
                ];
            }else if ($type ==2){
                $where[] = [
                    ['deleted','=',0],['isverify','=',1],['status','=',1]
                ];
            }else{
                $where[] = [
                    ['deleted','=',0],['status','=',$type]
                ];
            }
        }else{
            $where[] =[['openid','=',$openid]];
        }
        $where[] =[['tomember','=','']];
        $groupmodel =(new MallGroupsOrder());
        try {
            $list= $groupmodel
                ->field('id,ordersn,goods_id,goodslogo,goods_name,groupnum,price,payprice,status as orderstatus,create_time,create_time as end_time,isverify,success')
                ->where($where)
                ->order('orderstatus desc,create_time desc')
                ->page($page,10)
                ->select()
                ->toArray();

        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }

        if($list){
            $shoptime =(new Member())->getSystenConfig('shoptime');
            foreach ($list as $k=>$v){
                $cinfo =(new Group())->getGoodsInfo([['id','=',$v['goods_id']]],'short_title');
                $goodslist[0]=array(
                    'id'=>$v['goods_id'],
                    'goods_name'=>$v['goods_name'],
                    'logo'=>$v['goodslogo'],
                    'total'=>$v['groupnum'],
                    'price' =>$v['price'],
                    'title_desc'=>!empty($cinfo)? $cinfo['short_title']:''
                );
                $list[$k]['child'] =$goodslist;
                unset($list[$k]['goods_id']);
                unset($list[$k]['goodslogo']);
                unset($list[$k]['goods_name']);


                $left_time =$v['end_time']+$shoptime*60-time();
                if($left_time>0){
                    $day = intval($left_time / 86400);//天
                    $hour = intval((($left_time / 86400) - $day) * 24);//小时
                    $minute = intval((((($left_time / 86400) - $day) * 24) - $hour) * 60);//分钟
                    $second = intval(((((((($left_time / 86400) - $day) * 24) - $hour) * 60) - $minute) * 60));//秒
                    $list[$k]['end_time'] =$minute . '分钟' . $second . '秒';
                }else{
                    $list[$k]['end_time']='0秒';
                }

                switch($v['orderstatus']){
                    case '0':
                        $list[$k]['statusname'] ='待支付';
                        break;
                    case '1':
                        if($v['isverify']==0){
                            $list[$k]['statusname'] ='待核销';
                        }else{
                            $list[$k]['statusname'] ='已完成';
                        }
                        break;
                    case '2':
                        if($v['isverify']==0){
                            $list[$k]['statusname'] ='待核销';
                        }else{
                            $list[$k]['statusname'] ='已完成';
                        }
                        break;
                    case '3':
                        $list[$k]['statusname'] ='售后中';
                        break;
                    case '4':
                        $list[$k]['statusname'] ='已退款';
                        break;
                    default:
                        $list[$k]['statusname'] ='已取消';
                        break;
                }
            }
        }
        return $list;
    }

    /**
     * 我的转赠订单记录
     * @param $openid
     * @param $page
     * @return array
     * @throws Exception
     */
    public function getGroupsByOtherOrder($openid,$page){
        $where="((openid='".$openid."' and tomembertime>0) or tomember='$openid') and status=1 and isverify=0";
        $groupmodel =(new MallGroupsOrder());
        try {
            $list= $groupmodel
                ->field('id,openid,ordersn,goods_id,goodslogo,isverify,goods_name,groupnum,price,payprice,status as orderstatus,create_time,create_time as end_time,tomember')
                ->where($where)
                ->order('orderstatus desc,create_time desc')
                ->page($page,10)
                ->select()
                ->toArray();
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }

        if($list){
            $minfo =[];
            foreach ($list as $k=>$v){
                $cinfo =(new Group())->getGoodsInfo([['id','=',$v['goods_id']]],'short_title');
                if($v['tomember']){
                    $minfo =(new Wechat())->getOpenidById($v['openid']);
                }
                $list[$k]['fromnickName'] =$minfo['nickName']??'';
                $list[$k]['avatarUrl']    =$minfo['avatarUrl']??'';

                if($v['tomember'] == $openid){
                    $list[$k]['fromme'] =1; // 转给我的
                }else{
                    $list[$k]['fromme'] =0;  // 转出去的
                }
                $goodslist[0]=array(
                    'id'=>$v['goods_id'],
                    'goods_name'=>$v['goods_name'],
                    'logo'=>$v['goodslogo'],
                    'total'=>$v['groupnum'],
                    'price' =>$v['price'],
                    'title_desc'=>$cinfo['short_title']
                );
                $list[$k]['child'] =$goodslist;
                unset($list[$k]['goods_id']);
                unset($list[$k]['goodslogo']);
                unset($list[$k]['goods_name']);

                switch($v['orderstatus']){
                    case '0':
                        $list[$k]['statusname'] ='待支付';
                        break;
                    case '1':
                        if($v['isverify']==0){
                            $list[$k]['statusname'] ='待核销';
                        }else{
                            $list[$k]['statusname'] ='已完成';
                        }
                        break;
                    case '4':
                        $list[$k]['statusname'] ='售后';
                        break;
                    default:
                        $list[$k]['statusname'] ='已取消';
                        break;
                }
            }
        }
        return $list;
    }
    /**
     * @param $opneid
     * @param $page
     * @return array
     * @throws Exception
     */
    public function getGroupsByOrderHx($keyword,$openid,$page,$isverify=1){
        $where =" deleted=0 and isverify=".$isverify." and status=1 and openid ='$openid'";
        if($keyword){
            $where .= " and ((ordersn like '%".$keyword."%') or (goods_name like '%".$keyword."%'))";
        }

        $groupmodel =(new MallGroupsOrder());
        try {
            $list= $groupmodel
                ->field('id,ordersn,goods_id,goodslogo,goods_name,groupnum,price,payprice,status as orderstatus,create_time,create_time as end_time,isverify,verifytime')
                ->where($where)
                ->order('orderstatus desc,create_time desc')
                ->page($page,10)
                ->select()
                ->toArray();

        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }

        if($list){
            foreach ($list as $k=>$v){
                $cinfo =(new Group())->getGoodsInfo([['id','=',$v['goods_id']]],'short_title');
                $goodslist[0]=array(
                    'id'=>$v['goods_id'],
                    'goods_name'=>$v['goods_name'],
                    'logo'=>$v['goodslogo'],
                    'total'=>$v['groupnum'],
                    'price' =>$v['price'],
                    'title_desc'=>$cinfo['short_title']
                );
                $list[$k]['child'] =$goodslist;
                unset($list[$k]['goods_id']);
                unset($list[$k]['goodslogo']);
                unset($list[$k]['goods_name']);
            }
        }
        return $list;
    }

    public function getGroupsByOrderHxManage($keyword,$openid,$page,$isverify,$startime='',$endtime=''){
        $where =" deleted=0 and status=1";
        if($keyword){
            $where .= " and ((ordersn like '%".$keyword."%') or (goods_name like '%".$keyword."%'))";
        }
        if($startime){
            $where .=" and create_time >= " .strtotime($startime);
        }
        if($endtime){
            $where .= " and create_time <=" .strtotime($endtime);
        }
        if(intval($isverify)>0){
            $where .= " and isverify=0";
        }
        $manager =(new MallManager())->where([['openid','=',$openid],['applystatus','=',1]])->find();
        if(!$manager){
            return [];
        }
        $where .=" and manager_id=".$manager['id'];
        $groupmodel =(new MallGroupsOrder());
        try {
            $list= $groupmodel
                ->field('id,ordersn,goods_id,goodslogo,goods_name,groupnum,price,payprice,status as orderstatus,create_time,create_time as end_time,isverify,verifytime')
                ->where($where)
                ->order('orderstatus desc,create_time desc')
                ->page($page,10)
                ->select()
                ->toArray();

        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }

        if($list){
            foreach ($list as $k=>$v){
                $cinfo =(new Group())->getGoodsInfo([['id','=',$v['goods_id']]],'short_title');
                $goodslist[0]=array(
                    'id'=>$v['goods_id'],
                    'goods_name'=>$v['goods_name'],
                    'logo'=>$v['goodslogo'],
                    'total'=>$v['groupnum'],
                    'price' =>$v['price'],
                    'title_desc'=>$cinfo['short_title']
                );
                $list[$k]['child'] =$goodslist;
                unset($list[$k]['goods_id']);
                unset($list[$k]['goodslogo']);
                unset($list[$k]['goods_name']);
            }
        }
        return $list;
    }



    /**
     * 获取用户最近一次填写订单地址记录
     * @param $openid
     * @return mixed
     */
    public function  getLastOrder($openid){
        try{
            $orders= (new MallGroupsOrder())->field('realname,mobile')->where("openid='$openid'")->order('create_time desc')->find();
        }catch (\Exception $e){
            throw new Exception($e->getMessage());
        }
        return $orders;
    }
}